﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Timers;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace VirtualVisionSpace
{
    /// <summary>
    /// 提供随机变化的环境
    /// </summary>
    public class RandomEnvironment : EnvironmentBase
    {
        Bitmap[] images = new Bitmap[10];
        Bitmap imageObject = new Bitmap(50, 50);
        Point pointObject = new Point(50, 50);
        public RandomEnvironment(Size size)
            : base(size)
        {
            for (int i = 0; i < images.Length; i++)
            {
                images[i] = new Bitmap(size.Width, size.Height);
                GetRandomImage(images[i]);
            }
            //Graphics G = Graphics.FromImage(imageObject);
            //G.Clear(Color.Red);
            GetRandomImage(imageObject);
        }

        protected override void OnEnvironmentChanged(Bitmap environment)
        {
            //Bitmap image = images[random.Next(images.Length)];
            GetRandomImage(images[0]);
            CopyBitmap(images[0], new Rectangle(new Point(), size), environment, new Rectangle(new Point(), size));
            
            Graphics G = Graphics.FromImage(environment);
            if (pointObject.X % 5 == 0) GetRandomImage(imageObject);
            G.DrawImage(imageObject, pointObject);
            //G.DrawImage(imageObject, 50,50);
            this.pointObject.Offset(1, 1);
            this.pointObject.X %= this.size.Width;
            this.pointObject.Y %= this.size.Height;
        }

        //获取随机图像
        public void GetRandomImage(Bitmap image)
        {
            BitmapData data = image.LockBits(
                new Rectangle(0, 0, image.Width, image.Height),
                //new Rectangle(0, 0, 10, 10),
                ImageLockMode.ReadWrite,
                PixelFormat.Format24bppRgb);

            unsafe
            {
                byte* pData = (byte*)data.Scan0.ToPointer();
                for (int h = 0; h < image.Height; h++)
                {
                    for (int w = 0; w < image.Width; w++)
                    {//注意：扫描宽度以image.Width为准，指针宽度以data.Stride为准
                        int index = h * data.Stride + w * 3;
                        pData[index] = //(byte)random.Next(256);
                        pData[index + 1] = //(byte)random.Next(256);
                        pData[index + 2] = (byte)random.Next(byte.MaxValue);
                    }
                }
            }

            image.UnlockBits(data);
        }
    }
}
